var express = require('express');
var app = express();
var session = require('express-session');
var bodyparser = require('body-parser');

app.set('views', __dirname);
app.set('view engine', 'html');
app.engine('html', require('ejs').__express);

app.use(bodyparser.json());
app.use(bodyparser.urlencoded({ extended: true }));


app.use(session({
    secret :  'secret', // 对session id 相关的cookie 进行签名
    resave : true,
    saveUninitialized: false    // 是否保存未初始化的会话
}));

app.get('/', function (req, res) {
    if(req.session.userName){
        res.render('home',{username : req.session.userName});
    }else{
        res.redirect('login');
    }
});

app.get('/login', function(req, res){
    if(req.session.userName) {
            res.render('home',{username : req.session.userName});
    } else {
        res.sendFile(__dirname + '/login.html')
    }
});

app.post('/login', function(req, res){
    if(req.body.username == 'admin' && req.body.pwd == 'admin123'){
        req.session.userName = req.body.username;
        res.redirect('/');
    }
    else{
        res.json({ret_code : 1, ret_msg : '账号或密码错误'});
    }
});

app.get('/logout', function (req, res) {
    req.session.userName = null;
    res.redirect('login');
});

app.get('/*', function(req, res){
    if(req.session.userName) {
        res.render('home',{username : req.session.userName});
    } else {
        res.sendFile(__dirname + '/login.html')
    }
});

app.listen(5001,function () {
    console.log('http://127.0.0.1:5001')
})